package org.com.ashen.web.controller.sys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.com.ashen.client.service.ISMSChargeService;
import org.com.ashen.client.service.ISMSPINService;
import org.com.ashen.client.service.ISMSSendLogService;
import org.com.ashen.common.common.HttpResult;
import org.com.ashen.common.common.smscharge.SMSChargeDTO;
import org.com.ashen.common.common.smscharge.SMSChargeReqDTO;
import org.com.ashen.common.common.smspin.SMSPINDTO;
import org.com.ashen.common.common.smspin.SMSPINRedDTO;
import org.com.ashen.common.common.smssendlog.SMSSendLogDTO;
import org.com.ashen.common.common.smssendlog.SMSSendLogReqDTO;
import org.com.ashen.dal.dataobject.SmsReport;
import org.com.ashen.service.config.JdbcConfig;
import org.com.ashen.service.service.smssendlogmanage.sms.AliyunSmsUtil;
import org.com.ashen.service.service.smssendlogmanage.sms.YimeiSmsUtil;
import org.com.ashen.service.service.smssendlogmanage.sms.param.*;
import org.com.ashen.service.util.CodeUtil;
import org.com.ashen.service.util.DBUtil;
import org.com.ashen.web.constant.CommonUtils;
import org.com.ashen.web.constant.UrlConstant;
import org.com.ashen.web.execute.CommonExecute;
import org.com.ashen.web.execute.CommonExecutor;
import org.com.ashen.web.param.GetSysTestParam3;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
public class SmsController {
 
	@Resource(name = "jdbcConfig")
	private JdbcConfig jdbcConfig;

	@Resource(name = "sMSChargeService")
	private ISMSChargeService smsChargeService;

	@Resource(name = "sMSSendLogService")
	private ISMSSendLogService sMSSendLogService;

	@Resource(name = "sMSPINService")
	private ISMSPINService sMSPINService;

	private static Logger logger = Logger.getLogger(SmsController.class.getName());
	private String isencode ="";

	
	/**
	 * 短信充值
	 */
	@RequestMapping(value = UrlConstant.SMS_RECHARGE,produces = CommonUtils.CONTENT_TYPE)
	@ResponseBody
	public String SmsRecharge(final HttpServletRequest request,final HttpServletResponse response) throws IOException {
		String result = CommonExecutor.execute(request, response, SMSRechargeParam.class,
 				new CommonExecute<SMSRechargeParam>() {
				@Override
				public HttpResult<SMSChargeDTO> execute(SMSRechargeParam param) {
					SMSChargeReqDTO smsChargeReqDTO = new SMSChargeReqDTO();
					smsChargeReqDTO.setRealCharge(param.getRealCharge());
					smsChargeReqDTO.setSMSCharge(param.getSMSCharge());
					smsChargeReqDTO.setMemo(param.getMemo());
					smsChargeReqDTO.setStatusTime(param.getStatusTime());
					smsChargeReqDTO.setUserId(param.getUserId());
					smsChargeReqDTO.setPrivateAPPSecret(param.getPrivateAPPSecret());
					return smsChargeService.insert(smsChargeReqDTO);
				}
		});
		return result.replace("\\\"", "\"").replace("\"[", "[").replace("]\"", "]").replace("\"{", "{").replace("}\"", "}");
	}
	
	
	/**
	 * 查询余额
	 */
	@RequestMapping(value = UrlConstant.SMS_GETBALANCE,produces = CommonUtils.CONTENT_TYPE)
	@ResponseBody
	public String SmsGetBalance(final HttpServletRequest request,final HttpServletResponse response) throws IOException {
		String result = CommonExecutor.execute(request, response, RechargeParam.class,
 				new CommonExecute<RechargeParam>() {
				@Override
				public HttpResult<String> execute(RechargeParam param) {
					String str = "查询余额为10000元";
					logger.error("查询余额："+str);
					return HttpResult.successResult(str);
					}
				});
		return result.replace("\\\"", "\"").replace("\"[", "[").replace("]\"", "]").replace("\"{", "{").replace("}\"", "}");
	}


	/**
	 * 查询状态
	 */
	@RequestMapping(value = UrlConstant.SMS_GETREPORT,produces = CommonUtils.CONTENT_TYPE)
	@ResponseBody
	public String SmsGetReport(final HttpServletRequest request,final HttpServletResponse response) throws IOException {
		String result = CommonExecutor.execute(request, response, RechargeParam.class,
				new CommonExecute<RechargeParam>() {
					@Override
					public HttpResult<List<SmsReport>> execute(RechargeParam param) {
						List<SmsReport> smsReports = new ArrayList<>();
						if(param.getSmschannel().equals("yimei")){
							smsReports =  YimeiSmsUtil.smsGetReport(param.getSmsid());
						}else if(param.getSmschannel().equals("aliyun")){
							smsReports =  AliyunSmsUtil.getReport(param.getMobile(),param.getRequesttime(),param.getSmsid());
						}
						return HttpResult.successResult(smsReports);
					}
				});
		return result.replace("\\\"", "\"").replace("\"[", "[").replace("]\"", "]").replace("\"{", "{").replace("}\"", "}");
	}


	/**
	 * 单条短信发送
	 */
	@RequestMapping(value = UrlConstant.SMS_SINGLESMS,produces = CommonUtils.CONTENT_TYPE)
	@ResponseBody
	public String SmsSinglesms(final HttpServletRequest request,final HttpServletResponse response) throws IOException {
		String result = CommonExecutor.execute(request, response, SmsSingleSmsParam.class,
				new CommonExecute<SmsSingleSmsParam>() {
					@Override
					public HttpResult<SMSSendLogDTO> execute(SmsSingleSmsParam param) {
						System.out.println(JSON.toJSONString(param));
						SMSSendLogReqDTO smsSendLogReqDTO = new SMSSendLogReqDTO();
						smsSendLogReqDTO.setSendTime(param.getSendTime());
						smsSendLogReqDTO.setUserId(param.getUserId());
						smsSendLogReqDTO.setPrivateAPPSecret(param.getPrivateAPPSecret());
						smsSendLogReqDTO.setMobile(param.getMobile());
						smsSendLogReqDTO.setCustomSmsId(param.getCustomSmsId());
						smsSendLogReqDTO.setTemplateCode(param.getTemplateCode());
						smsSendLogReqDTO.setSmscontent(param.getSmscontent());
						return sMSSendLogService.insert(smsSendLogReqDTO);
					}
				});
		result = result.replace("\\\"", "\"").replace("\"[", "[").replace("]\"", "]").replace("\"{", "{").replace("}\"", "}");
		return result;
	}



	/**
	 * 多条短信发送
	 */
	@RequestMapping(value = UrlConstant.SMS_MULTISMS,produces = CommonUtils.CONTENT_TYPE)
	@ResponseBody
	public String SmsMultisms(final HttpServletRequest request,final HttpServletResponse response) throws IOException {
		String result = CommonExecutor.execute(request, response, SmsBatchSmsParam.class,
 				new CommonExecute<SmsBatchSmsParam>() {
				@Override
				public HttpResult<SMSSendLogDTO> execute(SmsBatchSmsParam param) {
					System.out.println(JSON.toJSONString(param));
					SMSSendLogReqDTO smsSendLogReqDTO = new SMSSendLogReqDTO();
					smsSendLogReqDTO.setSendTime(param.getSendTime());
					smsSendLogReqDTO.setUserId(param.getUserId());
					smsSendLogReqDTO.setPrivateAPPSecret(param.getPrivateAPPSecret());
					String mobiles = Arrays.toString(param.getMobiles() );
					mobiles = mobiles.replace("[[","").replace("]]","");
					smsSendLogReqDTO.setMobiles(mobiles.split(","));
					smsSendLogReqDTO.setCustomSmsId(param.getCustomSmsId());
					smsSendLogReqDTO.setTemplateCode(param.getTemplateCode());
					smsSendLogReqDTO.setSmscontent(param.getSmscontent());
					return sMSSendLogService.insert(smsSendLogReqDTO);
					}
				});
		return result.replace("\\\"", "\"").replace("\"[", "[").replace("]\"", "]").replace("\"{", "{").replace("}\"", "}");
	}
	
	
	/**
	 * 校验code
	 *
	 */
	@RequestMapping(value = UrlConstant.SMS_CHECKSMS,produces = CommonUtils.CONTENT_TYPE)
	@ResponseBody
	public String SmsChecksms(final HttpServletRequest request,final HttpServletResponse response) throws IOException {
		String result = CommonExecutor.execute(request, response, SmsCheckParam.class,
 				new CommonExecute<SmsCheckParam>() {
				@Override
				public HttpResult<SMSPINDTO> execute(SmsCheckParam param) {
					System.out.println(JSON.toJSONString(param));
					SMSPINRedDTO sMSPINRedDTO = new SMSPINRedDTO();
					sMSPINRedDTO.setPin(param.getPin());
					sMSPINRedDTO.setMobile(param.getMobile());
					sMSPINRedDTO.setSendTime(param.getSendTime());
					sMSPINRedDTO.setPrivateAPPSecret(param.getPrivateAPPSecret());
					sMSPINRedDTO.setUserId(param.getUserId());
					return sMSPINService.updatePin(sMSPINRedDTO);
				}
			});
		result = result.replace("\\\"", "\"").replace("\"[", "[").replace("]\"", "]").replace("\"{", "{").replace("}\"", "}");
			 if (isencode.equals("")) {
				result = CodeUtil.Encode(result);
			}
		return result;
	}

	
	
	/**
	 * 获取状态报告
	 */
	@RequestMapping(value = UrlConstant.SMS_STATUS,produces = CommonUtils.CONTENT_TYPE)
	@ResponseBody
	public String SmsStatus(final HttpServletRequest request,final HttpServletResponse response) throws IOException {
		String result = CommonExecutor.execute(request, response, RechargeParam.class,
 				new CommonExecute<RechargeParam>() {
				@Override
				public HttpResult<String> execute(RechargeParam param) {
					String str = "获取状态报告成功";
					logger.error("获取状态报告："+str);
					return HttpResult.successResult(str);
					}
				});
		return result.replace("\\\"", "\"").replace("\"[", "[").replace("]\"", "]").replace("\"{", "{").replace("}\"", "}");
	}
	
	
	/**
	 * 获取上行短信
	 */
	@RequestMapping(value = UrlConstant.SMS_MOREREQUEST,produces = CommonUtils.CONTENT_TYPE)
	@ResponseBody
	public String SmsMorerequest(final HttpServletRequest request,final HttpServletResponse response) throws IOException {
		String result = CommonExecutor.execute(request, response, RechargeParam.class,
 				new CommonExecute<RechargeParam>() {
				@Override
				public HttpResult<String> execute(RechargeParam param) {
					String str = "获取上行短信成功";
					logger.error("获取上行短信："+str);
					return HttpResult.successResult(str);
					}
				});
		return result.replace("\\\"", "\"").replace("\"[", "[").replace("]\"", "]").replace("\"{", "{").replace("}\"", "}");
	}
	
	
	
	
	
	
	
	
	
	public String RequsetSqlserver(GetSysTestParam3 param) {
		String sql = "{call UP_SAAS(?,?,?,?)}";
		 System.out.println(param.getInjson());
		Connection conn = DBUtil.getRtsaasConnection(jdbcConfig);
		CallableStatement call = null;  
	        try {  
	            call = conn.prepareCall(sql);
	            call.setString(1, param.getMethod());
	            if (param.getParse() == null) {
	            	 call.setString(2, "json");
				}else {
					 call.setString(2, param.getParse());
				}
	           
	           
	            call.setString(3, param.getInjson());
	           
	            call.registerOutParameter(4, Types.VARCHAR);
	              
	          
	            call.execute(); 
	            
	            String result="";

	            //这里可以获取多个结果集
	            
	            boolean bl = true;
            	while(bl) {
		            ResultSet rs = call.getResultSet();
		            if (rs != null) {
		            	
						while (rs.next()) {
							String results = (String) rs.getObject(1);
							if(result == "null") {
								results = "";
							}
							
							result += results; 
						}
					}
		            bl=call.getMoreResults();
	            }
            	
            	
            	if (result.equals("")) {
					result = call.getString(4);
				}
         
	            DBUtil.closeConnection(call, conn);
	            return result;
	        }catch (Exception e) {
	        	e.printStackTrace();
	        	System.out.println(e.getMessage());
				return "%errormessage#"+e.getMessage();
			}
	
	}
	
	
	
	
}
